package com.elmcode.server.service.impl;

import com.elmcode.server.constant.StatusConst;
import com.elmcode.server.dto.UserSaveInfo;
import com.elmcode.server.exception.ParamsException;
import com.elmcode.server.exception.UserException;
import com.elmcode.server.service.UserService;
import com.elmcode.server.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elmcode.common.utils.PageUtils;
import com.elmcode.common.utils.Query;

import com.elmcode.server.dao.UserDao;
import com.elmcode.server.entity.UserEntity;


@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    /**
     * elmcode:
     *   default:
     *     password: 123456
     */
    @Value("${elmcode.default.password}")
    private String defaultPassword;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        String name = (String) params.get("name");
        if(!StringUtils.isEmpty(name)){
            wrapper.like("login_name",name).or().like("name",name);
        }

        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public UserVo login(String loginName, String password) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().eq("login_name",loginName);

        UserEntity userEntity = this.baseMapper.selectOne(queryWrapper);

        //TODO 加密
        if(userEntity != null){
            //1、获取数据的password
            String passwordDb = userEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //2、密码匹配
            boolean matches = passwordEncoder.matches(password,passwordDb);
            //登录成功
            if(matches){
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(userEntity,userVo);
                log.info("登录成功:{}",userEntity);
                return userVo;
            }
        }
        return null;
    }

    @Override
    public void saveUser(UserSaveInfo userSaveInfo) throws UserException {
        //TODO 查询当前系统是否存在当前用户
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();

        if(userSaveInfo.getName() != null){
            queryWrapper.eq("name",userSaveInfo.getName());
        }
        if(userSaveInfo.getLoginName() != null){
            queryWrapper.or().eq("login_name",userSaveInfo.getLoginName());
        }
        /*
        TODO 身份证
        if(userSaveInfo.getCardId() != null){
            queryWrapper.eq("user_name",userSaveInfo.getCardId());
        }*/
        if(userSaveInfo.getPhone() != null){
            queryWrapper.or().eq("phone",userSaveInfo.getPhone());
        }

        UserEntity user = this.baseMapper.selectOne(queryWrapper);
        if(user == null){
            UserEntity userEntity = new UserEntity();
            BeanUtils.copyProperties(userSaveInfo,userEntity);

            userEntity.setCreateTime(new Date());
            userEntity.setUpdateTime(new Date());
            userEntity.setStatus(StatusConst.ACTIVE_STATUS);

            // 密码要进行加密存储
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(defaultPassword);
            userEntity.setPassword(encode);

            this.save(userEntity);
        }else {
            throw new UserException("用户已经存在");
        }
    }

    @Override
    public void updateUserInfo(Long id, UserSaveInfo userSaveInfo) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);

        BeanUtils.copyProperties(userSaveInfo,userEntity);

        this.baseMapper.updateById(userEntity);
    }

    @Override
    public void deleteById(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public void updateStatus(Long id, String status) throws ParamsException {
        if(status == null){
            throw new ParamsException("参数错误");
        }
        Integer updateStatus = -1;
        if(StatusConst.ACTIVE_STATUS_NAME.equals(status)){
            updateStatus = StatusConst.ACTIVE_STATUS;
        }
        if(StatusConst.INACTIVE_STATUS_NAME.equals(status)){
            updateStatus = StatusConst.INACTIVE_STATUS;
        }

        if(updateStatus != -1){
            UserEntity userEntity = new UserEntity();
            userEntity.setId(id);
            userEntity.setStatus(updateStatus);
            userEntity.setUpdateTime(new Date());
            this.baseMapper.updateById(userEntity);
        }else {
            throw new ParamsException("参数错误");
        }

    }

}